import { BaseFormText, BaseModalForm } from '@/components/base/BaseForm';
import { ModalFC } from '@/components/base/BaseModal';
import { UpdatePasswordParams, updateUserPassword } from '@/services/global';

const UpdatePasswordModal: ModalFC = (props) => {
  return (
    <BaseModalForm<UpdatePasswordParams>
      title='修改密码'
      {...props}
      onFinish={async (values) => {
        const { ok } = await updateUserPassword(values);
        return ok;
      }}
      labelCol={{ style: { width: 80 } }}
      autoComplete='off'
    >
      <BaseFormText.Password
        label='旧密码'
        name='oldPassword'
        placeholder='请输入旧密码'
        help='旧密码应为6-20位，需包含大写字母/小写字母/数字/特殊字符(~!@#$%^&*)'
        fieldProps={{
          readOnly: true,
          onFocus: (e) => {
            e.target.removeAttribute('readonly');
          }
        }}
        rules={[
          { required: true, message: '请输入旧密码' },
          () => ({
            validator(_, value) {
              if (!/^[0-9a-zA-Z~!@#$%^&*]{6,20}$/g.test(value)) {
                return Promise.reject(
                  new Error('旧密码应为6-20位，只能输入大写字母/小写字母/数字/特殊字符(~!@#$%^&*)')
                );
              }
              return Promise.resolve();
            }
          })
        ]}
      />
      <BaseFormText.Password
        label='新密码'
        name='newPassword'
        placeholder='请输入新密码'
        help='密码应为6-20位，需包含大写字母、小写字母、数字以及特殊字符(~!@#$%^&*)'
        fieldProps={{
          readOnly: true,
          onFocus: (e) => {
            e.target.removeAttribute('readonly');
          }
        }}
        rules={[
          { required: true, message: '请输入新密码' },

          ({ getFieldValue }) => ({
            validator(_, value) {
              if (
                !/^\S*(?=\S{6,20})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[~!@#$%^&*])\S*$/.test(
                  value
                )
              ) {
                return Promise.reject(
                  new Error('密码应为6-20位，需包含大写字母、小写字母、数字以及特殊字符(~!@#$%^&*)')
                );
              }
              if (getFieldValue('oldPassword') === value) {
                return Promise.reject(new Error('新密码不能与旧密码相同！'));
              }
              return Promise.resolve();
            }
          })
        ]}
      />
      <BaseFormText.Password
        label='确认密码'
        name='confirmPassword'
        placeholder='请再次输入新密码'
        fieldProps={{
          readOnly: true,
          onFocus: (e) => {
            e.target.removeAttribute('readonly');
          }
        }}
        rules={[
          { required: true, message: '请再次输入新密码' },
          ({ getFieldValue }) => ({
            validator(_, value) {
              if (!value || getFieldValue('newPassword') === value) {
                return Promise.resolve();
              }
              return Promise.reject(new Error('您输入的两个密码不匹配！'));
            }
          })
        ]}
      />
    </BaseModalForm>
  );
};

export default UpdatePasswordModal;
